//
//  MessageCircleViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/29.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

class MessageCircleViewController: RootViewController, UITableViewDelegate, UITableViewDataSource,CircleViewTableViewCellDelegate {
    
    @IBOutlet weak var mainTableView: UITableView!
    var bannerData:[BannerModel] = []
    var data:[CircleModel] = []

    let bannerHeight: CGFloat = 211
    let pageControlHeight: CGFloat = 25
    let consultationHeight: CGFloat = 125
    
    lazy var bannerView: FSPagerView = {
        
        let bannerView = FSPagerView()
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: ConsultationViewController.bannerHeight))
        bannerView.delegate = self
        bannerView.dataSource = self
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 3.0
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        return bannerView
    }()
    lazy var pageControl: FSPageControl = {
        let pageControl = FSPageControl()
        pageControl.frame = CGRect(x: 0, y: bannerView.height - 100, width: bannerView.width, height: 100)
        pageControl.numberOfPages = bannerData.count
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.setFillColor(.gray, for: .normal)
        pageControl.setFillColor(.white, for: .selected)
        pageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: 5, height: 5),                 cornerRadius: 2.5), for: .normal)
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 5, height: 5)), for: .selected)
        pageControl.itemSpacing = 8
        return pageControl
    }()
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()

    var page:Int = 0
    var totalPage:Int = 0
    var rightSelect = false

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setNavigationColor(colorState: .black)

        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setUI() {
        self.titleLabel(text: "圈子", nil)
        mainTableView.register(UINib(nibName: "\(CircleViewTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        mainTableView.delegate = self
        mainTableView.dataSource = self
        mainTableView.tableHeaderView = setBannerData()
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTableView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)

        self.fetchBannerList(type: 10)

        self.headerRefresh()
    }
    
    // MARK: - tableViewDatasource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CircleViewTableViewCell
        cell?.showData(model: data[indexPath.row])
        cell?.delegate = self
        return cell!
    }
    
    // MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let messageCircleDetailVC = MessageCircleDetailViewController(nibName: "\(MessageCircleDetailViewController.self)", bundle: nil)
        let model: CircleModel? = data[indexPath.row]
        messageCircleDetailVC.titleLabel(text: (model?.circleName)!, nil)
        messageCircleDetailVC.showRightButtonType = .share
        messageCircleDetailVC.circieId = model?.id
        self.navigationController?.pushViewController(messageCircleDetailVC, animated: true)
    }
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        if kind == UICollectionElementKindSectionHeader {
//            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath)
//            headerView.addSubview(setBannerData())
//            return headerView
//        } else {
//            let foot = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "foot", for: indexPath)
//            return foot
//        }
//    }
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchCircleList(parameters: ["page":page,"pageSize":10])
    }
    
    func joinTap(model: CircleModel) {
        let messageCircleDetailVC = MessageCircleDetailViewController(nibName: "\(MessageCircleDetailViewController.self)", bundle: nil)
        messageCircleDetailVC.titleLabel(text: (model.circleName)!, nil)
        messageCircleDetailVC.showRightButtonType = .share
        messageCircleDetailVC.circieId = model.id
        self.navigationController?.pushViewController(messageCircleDetailVC, animated: true)
    }

    
    /// 获取圈子列表
    func fetchCircleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(circleUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.data.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = CircleModel(fromDic: dic)
                                            
                                            self.data.append(model)
                                        }
                                        if self.totalPage == self.data.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
    
    /// 获取banner数据
    func fetchBannerList(type:Int) -> Void {
        let requesturl = "\(BaseURL)\(bannerUlr)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: ["type":type] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        self.bannerData.removeAll()

                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = BannerModel(fromDic: dic)
                                            self.bannerData.append(model)

                                        }
                                        self.pageControl.numberOfPages = self.bannerData.count
                                        self.bannerView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
}

extension MessageCircleViewController: FSPagerViewDelegate, FSPagerViewDataSource, BottomShadow {
    
    func setBannerData() -> UIView {
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: bannerHeight))
        bannerView.delegate = self
        bannerView.dataSource = self
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 2
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        pageControl.frame = CGRect(x: 0, y: bannerView.height - pageControlHeight, width: bannerView.width, height: pageControlHeight)
        pageControl.numberOfPages = bannerData.count
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.itemSpacing = 8
        
        let mainView = UIView()
        var rect = bannerView.frame
        rect.size.height += 10
        mainView.frame = rect
        mainView.backgroundColor = ONColor.cellBGColor
        mainView.addSubview(bannerView)
        mainView.addSubview(pageControl)
        setShadow(view: bannerView, opacity: 0.5, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
        return mainView
    }
    
    func setConsultationCollectionView(arr:[GoodsModel]) -> UIView {
        let consultationCV: ConsultationCollectionView = ConsultationCollectionView()
        consultationCV.frame = CGRect(x: 0, y: bannerView.height + 10, width: ScreenWidth, height: consultationHeight)
        consultationCV.setData(arr: arr)
        consultationCV.delegateVc = self
        
        return consultationCV
    }
    
    // MARK:- FSPagerView DataSource
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannerData.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.isDescribeLabel = true
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
        
        let model = self.bannerData[index]
        if let cpath = model.image{
            let path:String = "\(BaseURL)\(cpath)"
            
            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            
            cell.imageView?.sd_setImage(with: url! as URL, completed: nil)
        }
        if let name = model.title{
            cell.textLabel?.text = name
        }
        
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        self.pageControl.currentPage = index
        let model = self.bannerData[index]
        bannerJump(model: model)
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex
    }
    
    
    @objc func returnRootVC() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    
    
}
//
//extension MessageCircleViewController: FSPagerViewDelegate, FSPagerViewDataSource {
//    func setBannerData() -> UIView {
//
//        let mainView = UIView()
//        var rect = bannerView.frame
//        rect.size.height += 10
//        mainView.frame = rect
//        mainView.backgroundColor = ONColor.cellBGColor
//        mainView.addSubview(bannerView)
//        mainView.addSubview(pageControl)
//
//        setShadow(view: bannerView, opacity: 0.5, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
//
//        return mainView
//    }
//
//    // MARK:- FSPagerView DataSource
//
//    public func numberOfItems(in pagerView: FSPagerView) -> Int {
//        return bannerData.count
//    }
//
//    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
//        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
//        cell.isDescribeLabel = false
//        cell.imageView?.contentMode = .scaleAspectFill
//        cell.imageView?.clipsToBounds = true
//        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
//        if pagerView == self.bannerView {
//            let model = self.bannerData[index]
//            if let cpath = model.image{
//                let path:String = "\(BaseURL)\(cpath)"
//
//                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//
//                cell.imageView?.sd_setImage(with: url! as URL, completed: nil)
//
//            }
//            if let name = model.title{
//                cell.textLabel?.text = name
//            }
//        }
//        return cell
//    }
//
//    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
//        pagerView.deselectItem(at: index, animated: true)
//        pagerView.scrollToItem(at: index, animated: true)
//        self.pageControl.currentPage = index
//        let model = self.bannerData[index]
//        bannerJump(model: model)
//    }
//
//    func pagerViewDidScroll(_ pagerView: FSPagerView) {
//        guard self.pageControl.currentPage != pagerView.currentIndex else {
//            return
//        }
//        self.pageControl.currentPage = pagerView.currentIndex
//    }
//}

